import React, {useEffect, useState} from 'react';
import {Button, Col, Divider, Row, Tag} from "antd";

/**
 * useEffect
 * @returns {JSX.Element}
 * @constructor
 */
export const UseEffectHooks = function (props) {
    console.log(props,'props');

    const [num,setNum] = useState(0);



    const handler = ()=>{
        console.log('我改变了num的值')
        setNum(num+1);
    }

    useEffect(()=>{
        console.log('只有num值改变时候我才被触发',num);
    },[num])

    useEffect(() => {
     console.log('每次都调用我');
    });


    useEffect(()=>{
        return () => {
            console.log('我会在组件销毁时被调用',num);//返回的小函数会在组件释放时候执行
        }
    },[num])

    //hooks不能放在任何的条件循环或判断里，必须必须要能触发到hooks
    // for (let i = 0; i < num; i++) {
    //     useEffect(()=>{
    //         console.log('call back return func');
    //     })
    // }//不可
    //
    // if(num > 5){
    //     useEffect(()=>{
    //         console.log('call back return func');
    //
    //     })
    // }//不可

    return (
        <>
            <Row>
                <Col push={4}>
                    {num}
                </Col>
                <Divider/>

                <Col push={4}>
                    <Button type={"primary"} onClick={handler}>触发num的变化以观察useEffect的调用时机</Button>
                </Col>


            </Row>
            <Divider/>

            <Row>
                <Col push={4}>
                    <Tag color={'blue'}>useEffect想在组件初始化时候执行查询</Tag>
                    <EffectFirstQueryHooks/>
                </Col>
            </Row>
        </>
    )

};

const  queryData = ()=>{
    return new Promise((resolve,reject)=>{
        resolve('hello world');
    });
}

const EffectFirstQueryHooks = ()=>{
    // useEffect(async () => {
    //     const data = await queryData();
    //     console.log(data);
    // }, []);//不行，async会返回Promise，但是useEffect要求必须返回函数供组件销毁时执行

    const [data,setData]=useState('');

    useEffect(() => {
        queryData().then(res=>{
            console.log(res);
            setData(res)
        })
    }, []);

    useEffect(() => {
        const query = async ()=>{
            const data =  await queryData();

            console.log(data);
        }
        query();
    }, []);

    return (
        <>
            我在这
            {data}
        </>
    )
}